package com.huxin.servelt;

import com.alibaba.fastjson.JSON;
import com.huxin.pojo.UserInfo;
import com.huxin.service.Userservice;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


@WebServlet("/user/login")
public class UserLoginServlet extends HttpServlet {
    private Userservice userservice=new Userservice();
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取前端传过来的账号 密码 验证码
        String s = req.getReader().readLine();
        UserInfo userInfo = JSON.parseObject(s, UserInfo.class);
        //获取session中的验证码
        String code = (String) req.getSession().getAttribute("code");
//        System.out.println(userInfo.getCode());
        if (code.equalsIgnoreCase(userInfo.getCode())){
            System.out.println("验证码正确");
            boolean b=userservice.login(userInfo.getUsername(),userInfo.getPassword());
//
//            System.out.println(b);
            if (b==true){
                //登录成功之后将该用户的id存进session
                UserInfo userInfo1=userservice.userLogin(userInfo.getUsername(),userInfo.getPassword());
                if (userInfo1.getStatus()==1){
                    req.getSession().setAttribute("userId",userInfo1.getAid());

                    //判断是否勾选记住我
                    String bb = userInfo.getJizhuwo();
                    if ("true".equals(bb)){
                        Cookie jizhuwo = new Cookie("jizhuwo",bb);
                        Cookie username = new Cookie("username",userInfo.getUsername());
                        Cookie password = new Cookie("password",userInfo.getPassword());

                        jizhuwo.setMaxAge(3600);
                        username.setMaxAge(3600);
                        password.setMaxAge(3600);
                        //响应中增加cookie
                        resp.addCookie(jizhuwo);
                        resp.addCookie(username);
                        resp.addCookie(password);
                    }

                    resp.getWriter().write("0");//登录成功
                }else{
                    resp.getWriter().write("3");//未在白名单
                }

            }else {

                resp.getWriter().write("2");//账号或密码错误
            }
        }else {
            resp.getWriter().write("1");//验证码错误
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }
}
